<?php
set_include_path ( $_SERVER ['DOCUMENT_ROOT'] );
include_once 'admin/includes/functions/admin-functions.php';
ini_set('display_errors',1);
ini_set('error_reporting',E_ALL ^ E_NOTICE ^ E_WARNING);

global  $CONFIG,$SMARTY,$DBobject;

echo " => Cron started";
$classTermObj = new ClassTermClass();
$enrol_obj = new Enrolment();

$events = array();
$instructorSend = array();
$error = array();

$weekday = date('l', strtotime('+1 days'));
$day = date('Y-m-d', strtotime('+1 days'));

//Only at THEM
if($_SERVER['REMOTE_ADDR']=='150.101.230.130' && !empty($_REQUEST['date'])){
	$day = date('Y-m-d', strtotime($_REQUEST['date']));
	$weekday = date('l', strtotime($_REQUEST['date']));
}


$devAdmin = "readysteadygokids@gmail.com-dev";
$subject = "Tomorrow's Attendance";
$from = (string) $CONFIG->company->name;
$fromEmail = 'noreply@'. str_replace('www.', '', $GLOBALS['HTTP_HOST']);
$COMP = json_encode($CONFIG->company);
$SMARTY->assign('COMPANY', json_decode($COMP,TRUE));
$SMARTY->assign('DOMAIN', "http://" . $GLOBALS['HTTP_HOST']);

try {
	// Get current terms
	$sql = "SELECT * FROM tbl_term WHERE term_deleted IS NULL AND term_published = 1 AND ( :day BETWEEN term_start_date AND term_end_date) ORDER BY term_start_date"; 
	if($terms = $DBobject->wrappedSql($sql, array(':day'=>$day))){
		
		// Get instructor list
		$sql = "SELECT admin_id, admin_name, admin_email FROM tbl_admin WHERE admin_deleted IS NULL AND admin_level > 1";
		if($instructors = $DBobject->wrappedSql($sql)){
			
			foreach($instructors as $i){
				if($i['admin_id'] != 104) continue;
				$data = array();
				$hasClass = false;
				
				foreach($terms as $t){
					// Calculate current week
					$week = $classTermObj->GetCurrentWeekByTermStartDate($t['term_start_date'], $day);
				
					// Get classes associated to the instructors for the current term 		
					$sql = "SELECT location_state, location_suburb, class_start_time, class_object_id, class_name, location_name, agegroup_name
					FROM tbl_class 
						LEFT JOIN tbl_classterm ON classterm_class_id = class_object_id 
						LEFT JOIN tbl_location ON location_object_id = class_location_id
						LEFT JOIN tbl_agegroup ON agegroup_id = class_agegroup_id
						LEFT JOIN	tbl_class_instructor ON class_instructor_class_id = class_id
					WHERE classterm_deleted IS NULL AND classterm_published = '1' AND classterm_term_id = :classterm_term_id 
						AND class_deleted IS NULL AND class_published = '1' 
						AND location_published = '1' AND location_deleted IS NULL AND agegroup_deleted IS NULL 
						AND class_weekday = :class_weekday AND class_instructor_deleted IS NULL AND class_instructor_flag = '1'
						AND class_instructor_admin_id = :class_admin_id
					GROUP BY class_object_id 
					ORDER BY location_state, location_suburb, class_start_time";
					$params = array (":classterm_term_id"=>$t['term_id'], ":class_weekday"=>$weekday, ":class_admin_id"=>$i['admin_id']);
					if($classes = $DBobject->wrappedSql($sql, $params)){	

						$instructorSend["{$i['admin_id']}"] = true; 
						foreach($classes as $c){
							// Get enrolments/student/user for each class 
							$sql = "SELECT enrolment_id, student_name, student_surname, student_dob, type_name, user_gname, user_surname, user_email, address_telephone 
								FROM tbl_enrolment 
									LEFT JOIN tbl_student ON student_id = enrolment_student_id 
									LEFT JOIN tbl_type ON type_code = enrolment_type
									LEFT JOIN tbl_user ON user_id = student_user_id 
									LEFT JOIN tbl_payment ON payment_id = enrolment_payment_id 
									LEFT JOIN tbl_address ON address_id = payment_billing_address_id 
								WHERE enrolment_deleted IS NULL AND student_deleted IS NULL AND user_deleted IS NULL
									AND enrolment_published = '1' AND type_deleted IS NULL AND payment_deleted IS NULL AND address_deleted IS NULL 
									AND enrolment_term_object_id = :enrolment_term_object_id AND enrolment_class_object_id = :enrolment_class_object_id
									AND enrolment_week = :enrolment_week 
								ORDER BY student_name, student_surname";
							$params = array (":enrolment_term_object_id"=>$t['term_object_id'], ":enrolment_week"=>$week, ":enrolment_class_object_id"=>$c['class_object_id']);
							if($enrolments = $DBobject->wrappedSql($sql, $params)){
								if(empty($data["{$t['term_object_id']}"])) {
									$data["{$t['term_object_id']}"] = $t;
									$data["{$t['term_object_id']}"]['week'] = $week;
								}
								$data["{$t['term_object_id']}"]['classes']["{$c['class_object_id']}"] = $c;
								$data["{$t['term_object_id']}"]['classes']["{$c['class_object_id']}"]['enrolments'] = $enrolments;
								$hasClass = true;
							}
						}
					}
				}
				if(!empty($instructorSend["{$i['admin_id']}"]) && $hasClass){
					$events['records']['email']["{$i['admin_email']}"] = $data;
					
					$SMARTY->assign('admin', $i);
					$SMARTY->assign('day', $day);
					$SMARTY->assign('data', $data);
				
					$body = $SMARTY->fetch('cron/table-class-list.tpl');
					print_r($body);
					//createBulkMail(array($i['admin_email']), $from, $fromEmail, $subject, $body);
				}
			}
			//	echo " => Emails sent: ". sendBulkMail() ; // "cron_email_queue.php" will send them
		}
	}

	
} catch (Exception $e) {
	$events['error'][] = "Error while running".$e;
}
//sendMail($devAdmin, $from, $fromEmail, "CRON JOB - $subject - $day", json_encode($events));
//createBulkMail(array($devAdmin), $from, $fromEmail, "CRON JOB - $subject - $day", json_encode($events));
echo " => Cron ended";
die();
